package com.shiningstars.activity;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.ScrollView;

import com.shiningstars.R;
import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.service.MSLocatorService;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.MsLocation;

public class MSLocatorActivity extends Activity implements Constants, Messages, Config {

	EditText editTextPlace = null;
	EditText editTextStayDuration = null;
	EditText editTextContactPerson = null;
	EditText editTextComments = null;
	EditText editTextPostedBy = null;
	EditText editTextPostedOn = null;
	Button buttonUpdateSave = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_ms_location);

			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			SplashPageActivity.showSplash = false;

			editTextPlace = (EditText) findViewById(R.id.msEditText1);
			editTextStayDuration = (EditText) findViewById(R.id.msEditText2);
			editTextContactPerson = (EditText) findViewById(R.id.msEditText3);
			editTextComments = (EditText) findViewById(R.id.msEditText4);
			editTextPostedBy = (EditText) findViewById(R.id.msEditText5);
			editTextPostedOn = (EditText) findViewById(R.id.msEditText6);
			buttonUpdateSave = (Button) findViewById(R.id.msUpdateSaveButton);

			displayMsLocation();

		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MSLocatorActivity.class.getName(), e);
		}
	}

	private void displayMsLocation() {
		DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());
		MsLocation msLocation = databaseHandler.getMsLocation();

		editTextPlace.setEnabled(false);
		editTextStayDuration.setEnabled(false);
		editTextContactPerson.setEnabled(false);
		editTextComments.setEnabled(false);

		if (null != msLocation) {
			editTextPlace.setText(msLocation.getPlace());
			editTextStayDuration.setText(msLocation.getStayDuration());
			editTextContactPerson.setText(msLocation.getContactPerson());
			editTextComments.setText(msLocation.getComments());
			editTextPostedBy.setText(msLocation.getPostedBy());
			editTextPostedOn.setText(msLocation.getPostedOn());
		} else {
			editTextPostedBy.setText(BLANK);
			editTextPostedOn.setText(BLANK);
		}

		buttonUpdateSave.setText(UPDATE_LOCATION);

		((ScrollView) findViewById(R.id.msScrollView)).fullScroll(ScrollView.FOCUS_UP);
	}

	public void updateOrSave(View v) {
		try {
			String buttonText = buttonUpdateSave.getText().toString();

			if (UPDATE_LOCATION.equals(buttonText)) {
				editTextPlace.setEnabled(true);
				editTextStayDuration.setEnabled(true);
				editTextContactPerson.setEnabled(true);
				editTextComments.setEnabled(true);

				Calendar c = Calendar.getInstance();
				int year = c.get(Calendar.YEAR);
				int month = c.get(Calendar.MONTH);
				int date = c.get(Calendar.DATE);

				String postedBy = Utilities.getSharedPreference(getApplicationContext(), NAME);
				String postedOn = Utilities.getDate(date, month, year);
				String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);

				editTextPlace.setText(BLANK);
				editTextStayDuration.setText(BLANK);
				editTextContactPerson.setText(BLANK);
				editTextComments.setText(BLANK);
				editTextPostedBy.setText(postedBy + NEW_LINE + mobileNumber);
				editTextPostedOn.setText(postedOn);

				buttonUpdateSave.setText(SAVE);

				((ScrollView) findViewById(R.id.msScrollView)).fullScroll(ScrollView.FOCUS_UP);
				editTextPlace.requestFocus();
			} else if (SAVE.equals(buttonText)) {
				MsLocation msLocation = new MsLocation();
				msLocation.setMsLocationId(0);
				msLocation.setPlace(editTextPlace.getText().toString());
				msLocation.setStayDuration(editTextStayDuration.getText().toString());
				msLocation.setContactPerson(editTextContactPerson.getText().toString());
				msLocation.setComments(editTextComments.getText().toString());
				msLocation.setPostedBy(editTextPostedBy.getText().toString());
				msLocation.setPostedOn(editTextPostedOn.getText().toString());
				msLocation.setIsSynced(N);
				msLocation.setIsNotified(N);
				msLocation.setCreatedDate(Calendar.getInstance().getTimeInMillis());

				DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());
				long count = databaseHandler.updateMsLocation(msLocation);

				if (count != -1) {
					AlertDialog.Builder builder = new AlertDialog.Builder(MSLocatorActivity.this);
					builder.setMessage(MS_LOCATION_UPDATED);
					builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							displayMsLocation();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();
				}

				if (!Utilities.isRunning(getApplicationContext(), MSLocatorService.class.getName())) {
					startService(new Intent(getApplicationContext(), MSLocatorService.class));
				}
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MSLocatorActivity.class.getName(), e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.ms_locator_menu, menu);

			String role = Utilities.getSharedPreference(getApplicationContext(), ROLE);
			if (ADMIN.equals(role)) {
				MenuItem menuItem = menu.findItem(R.id.menu_items);
				SubMenu subMenu = menuItem.getSubMenu();
				subMenu.add(ADMIN_MENU);
				subMenu.getItem(1).setIcon(R.drawable.ic_action_admin);
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MSLocatorActivity.class.getName(), e);
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			if (MY_FEEDBACK.equals(item.getTitle())) {
				Intent i = new Intent(MSLocatorActivity.this, MyFeedbackActivity.class);
				startActivity(i);
				finish();
			} else if (ADMIN_MENU.equals(item.getTitle())) {
				Intent i = new Intent(MSLocatorActivity.this, AdminActivity.class);
				startActivity(i);
				finish();
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MSLocatorActivity.class.getName(), e);
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(MSLocatorActivity.this);

			String buttonText = buttonUpdateSave.getText().toString();

			if (SAVE.equals(buttonText)) {
				builder.setMessage(CANCEL_MS_LOCATION_UPDATE_MSG);
				builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						displayMsLocation();
					}
				});
			} else {
				builder.setMessage(EXIT_MSG);
				builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				});
			}

			builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MSLocatorActivity.class.getName(), e);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		SplashPageActivity.showSplash = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (SplashPageActivity.showSplash) {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.activity_splash_page, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			findViewById(R.id.msTextView1).post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(findViewById(R.id.msTextView1), Gravity.CENTER, 0, 0);
				}
			});

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					popupWindow.dismiss();
				}
			}, SPLASH_TIME_OUT);

			SplashPageActivity.showSplash = false;
		}
	}
}